//
//  评价Ctr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/13.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import soapp
import MBProgressHUD
//import TPKeyboardAvoiding


public class GoodsCommentCtr: ListController {
    public var scheme = SaleScheme.normal
    
    public func createOneFinishedCMSection(goods:NSMutableDictionary) -> [[String:Any]] {
        let sec = [
            [
                "cellID":"goods",
                FK.fields:[
                    [
                        "__model":goods,
                        FK.field:StrField(id: "goods_info", defaultV: nil, need: true, hiden: false, rule:
                            JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请选择要评价的商品".loc, err_msg: "请选择要评价的商品".loc))
                    ]
                ],
            ],
            [
                "cellID":"content",
                "__model":goods
            ]
        ]
        return sec
    }
    
    func createOneWaitingCMSection(goods:NSMutableDictionary)->[[String:Any]] {
        
        let gid = goods.possible("goodsid","groups_goods_id", default: "")
        let oid = goods["optionid",""]
        let idV:[String:Any] = [
            "goodsid":gid,
            "optionid":oid,
        ]
        
        let sec:[[String:Any]] = [
            [
                "cellID":"goods",
                FK.fields:[
                    [
                        "__model":goods,
                        FK.value:(idV.rawJson ?? "{}"),
                        FK.field:StrField(id: "goods_info", defaultV: nil, need: true, hiden: false, rule:
                            JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请选择要评价的商品".loc, err_msg: "请选择要评价的商品".loc))
                    ]
                ],
            ],
            [
                "title":"内容".loc,
                "cellID":"text",
                FK.fields:[
                    [
                        FK.placeholder:"说说你的购物心得，分享给其他的小伙伴吧！".loc,
                        FK.field:StrField(id: "content", defaultV: nil, need: true, hiden: false, rule:
                            JoRule(reg: "^[\\s\\S]{10,200}$", nil_msg: "检查评论内容".loc, err_msg: "内容不得少于10个字符".loc))
                    ]
                ],
            ],
            [
                "title":"上传凭证".loc,
                "cellID":"files",
                FK.fields:[
                    [
                        FK.max_mum:"5",
                        FK.placeholder:"(支持jpg,png,jpeg最多5张，每张3M 以内)".loc,
                        FK.field:StrField(id: "images", defaultV: nil, need: true, hiden: false, rule:
                            JoRule(reg: ".{0,}", nil_msg: "请上传凭证".loc, err_msg: "请上传凭证".loc)),
                        ],
                ]
            ],
            [
                "title":"商品评分".loc,
                "cellID":"score",
                FK.fields:[
                    [
                        FK.placeholder:"评分".loc,
                        FK.value:"4",
                        FK.field:StrField(id: "level", defaultV: nil, need: true, hiden: false, rule:
                            JoRule(reg: "^[\\s\\S]{0,200}$", nil_msg: "给出您的评分".loc, err_msg: "给出您的评分".loc))
                    ]
                ],
                ],
            [
                "cellID":"anonymous",
                FK.fields:[
                    [
                        FK.options:[["id":"1","name":"匿名评论".loc]],
                        FK.selectMode:TagSelectMode.singleToggle.value,
                        FK.field:StrField(id: "isanonymous", defaultV: nil, need: true, hiden: false, rule:
                            JoRule(reg: "^[\\s\\S]{0,200}$", nil_msg: "请设置是否匿名".loc, err_msg: "请设置是否匿名".loc))
                    ]
                ],
                ]
        ]
        return sec
    }
    
    
    public var sections:TP.section{
        get{
            var goods = DataNode.path(node: "goods",mo.detail, value: NSMutableArray())
            if goods.count < 1{
                goods = DataNode.path(node: "__model.goods",mo.detail, value: NSMutableArray())
            }
            
            var sec:TP.section = TP.section()
            
            
            weak var wself = self
            goods.list { (one:NSMutableDictionary, i) in
                
                let isCMed = (one["comment.id",""].len > 0)
                guard let ws = wself else{return}
                if !isCMed
                {
                    var cm_section = ws.createOneWaitingCMSection(goods: one)
                    cm_section.append(["cellID":"submit","sectionID":"section\(i)"])
                    sec.append(cm_section)
                }
                else{
                    
                    sec.append(ws.createOneFinishedCMSection(goods: one))
                }
            }
            
            
            return sec
        }
    }
    
    let selector:TP.selector = [
        "cellID<goods>":OneGoodsCell.self,
        "cellID<score>":MallForm.ScoreCell.self,
        "cellID<text>":MallForm.GoodsCommentCell<line.px60>.self,
        "cellID<files>":MallForm.MGoodsUploadCell.self,
        "cellID<anonymous>":RadioOptionCell.self,
        "cellID<submit>":SumbmitCell.self,
        "cellID<content>":CommentCell.self,
        ]
    
    var submitSectionID = ""
    
    public override  func viewDidLoad() {
        tableView = TPKeyboardAvoidingTableView(frame: .zero, style: .plain)
        super.viewDidLoad()
        tableView.buildDynamicHeight()
        tableView.separatorStyle = .none
        title = "评价".loc
        tableView.backgroundColor = UIColor._tableBackground
        //        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(beginSubmit))
        //        self.navigationItem.rightBarButtonItem?.tintColor = UIColor(shex:UIColor.main_hex)
        mo_request_send()
        
    }
    
    public override func mo_request_send() {
        
        weak var wself = self
        loadingV.loading()
        JoTask().post.log.params(["orderid":orderID])._surl(scheme.getOrderCommentURL).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                    return
                }
            }
            wself?.mo_request_alert(msg: msg, title: "", bt_title: "重试".loc)
            }.run()
    }
    
    public override func mo_detail_reload() {
        
        tableView.load(sections: sections, selector: selector)
        tableView.reloadData()
        
    }
    
    
    
    public override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        if actionID == "updateTable"
        {
            tableView.beginUpdates()
            tableView.endUpdates()
        }
        if actionID == "submit"{
            submitSectionID = model["sectionID",""]
            let section = DataNode.path(node: submitSectionID, tableView.model, value: NSMutableArray())
            if section.count > 0
            {
                beginSubmit(section: section)
            }
        }
    }
}

extension GoodsCommentCtr
{
    
    @objc func beginSubmit(section:NSMutableArray) {
        let info = JoPaw.paw(list: section)
        if info.validate{
            var values = info.values
            var files = [[String:Any]]()
            if let imgs = values["images"] as? String
            {
                (imgs.JsonArray ?? NSMutableArray()).list({ (one:NSMutableDictionary, i) in
                    if one["path",""].len > 2
                    {
                        files.append(
                            [
                                "path":one["path",""],
                                ]
                        )
                    }
                })
                values.removeValue(forKey: "images")
            }
            let ps = values
            uploadFiles(values: ps, files: files)
        }
    }
    
    
    func uploadFiles(values:[String:Any],files:[[String:Any]]) {
        if files.count < 1
        {
            var vs = values
            vs["thumbs"] = "[]"
            commitAction(params: vs)
            return
        }
        
        let ls = files.mutable_array
        
        let tasks = ls.map { (one) -> UploadImageTask in
            let task = UploadImageTask()
            task.url = _SURL.uploadImage.url
            task.model = one as! NSMutableDictionary
            return task
        }
        
        weak var wself = self
        
        
        var hud:MBProgressHUD? = MBProgressHUD.init(view: wself!.navigationController!.view)
        if hud == nil{
            hud = MBProgressHUD.showAdded(to: wself!.navigationController!.view, animated: true)
        }
        
        hud?.minSize = [150,100]
        hud?.label.text = "正在上传图片".loc
        hud?.mode = .indeterminate
        
        AsyncQue.default.start(tasks: tasks) { (progress) in
            switch progress  {
            case .failed(count: _, task: _):
                hud?.hide(animated: true)
                "文件上传失败,请重试".loc.alert()
            case .success:
                var img_urls = [String]()
                for one in tasks{
                    img_urls.append(one.model["__url",""])
                }
                
                var vs = values
                vs["thumbs"] = img_urls
                //                vs["thumbs"] = img_urls.joined(separator: "|")
                wself?.commitAction(params: vs)
            case .continue(count: let i, task:_):
                hud?.label.text = "\("正在上传图片".loc)(\(i)/\(tasks.count))"
                break
            }
        }
    }
    var orderID:String{
        get{
            return mo.model.possible("order.id", default: "")
        }
    }
    
    
    func commitAction(params:[String:Any]) {
        var ps = params
        
        weak var wself = self
//        var hud:MBProgressHUD? = MBProgressHUD.init(view: wself!.navigationController!.view)
//        if hud == nil{
//            hud = MBProgressHUD.showAdded(to: wself!.navigationController!.view, animated: true)
//        }
//
        HUD.share.show().mode(.indeterminate).label(text: "正在提交信息".loc)
        
        let ps_dict = ps.mutable_dictionary
        if ps_dict["isanonymous",""] == ""
        {
            ps["isanonymous"] = false.tag
        }
        
        if let goods_info = ps_dict["goods_info",""].JsonDictionary{
            ps.removeValue(forKey: "goods_info")
            ps = ps + goods_info.swift_dictionary
        }
        
        let info:[String:Any] = ["orderid":orderID,"comments":(ps.rawJson ?? "{}")]
        JoTask().post.log.log_response()._surl(scheme.submitCommentURL).params(info).json_handle { (status, msg, obj, resp) in
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.successComment(info: dict)
                    HUD.share.hide(animated: true, delay: 0)
//                    hud?.hide(animated: true)
                    return
                }
            }
            HUD.share.tip(.error(msg: msg)).hide(animated: true, delay: 2.5)
            }.run()
    }
    
    func successComment(info:NSMutableDictionary) {
        
        let numStr = submitSectionID.replacingOccurrences(of: "section", with: "")
        if let section = Int(numStr)
        {
            
            tableView.model[submitSectionID] = self.createOneFinishedCMSection(goods: info).mutable_array
            let sec = IndexSet(integer:section)
            tableView.reloadSections(sec, with: .fade)
        }
        
        "提交成功,感谢您的评价".loc.alert()
        __post(notify: Goods.Notice.goodsOrderChange)
        __post(notify: Goods.Notice.groupOrderChange)

        //        weak var wself = self
        //        wself?.navigationController?.popViewController(animated: true)
        //        JoAlertView(info: "提示","信息提交成功,感谢您的评价").append(title: "确定", style: UIAlertActionStyle.cancel) {
        //        }.show(at: self.navigationController)
    }
    
    
    
    
    
    
    
    
    
    
}

